package com.guodi.common.utils;

import org.mozilla.universalchardet.UniversalDetector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* @描述：字符串编码操作类
* @作者：邹艺
* @日期：2019/5/31 11:35
**/
public class EncodingUtil {

    private static Logger logger = LoggerFactory.getLogger(EncodingUtil.class);

    private static Pattern regex = Pattern.compile("[\u4e00-\uff09]");
    //中文编码
    public static String encode(String str) {
        Matcher m = regex.matcher(str);
        StringBuffer b = new StringBuffer();
        try {
            while (m.find()) {
                String key = m.group();
                m.appendReplacement(b, URLEncoder.encode(key, "UTF-8"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        m.appendTail(b);
        return b.toString();
    }


    /**
     * 获取当前系统支持的全部编码集
     * @return
     */
    public static List<String> listAllCharsets(){
        SortedMap<String, Charset> stringCharsetSortedMap = Charset.availableCharsets();
        ArrayList<String> charsetList = new ArrayList<>(stringCharsetSortedMap.keySet());
        return charsetList;
    }


    /**
     * 判断当前字节数组的编码，如果无法获取，默认UTF-8
     * @return
     */
    public static String getCharset(byte[] strData){
        // 默认UTF-8
        String defaultCharset = Charset.defaultCharset().name();
        try {
            UniversalDetector detector = new UniversalDetector(null);
            // 处理数据
            detector.handleData(strData,0,strData.length);
            detector.dataEnd();
            // 获取编码格式
            String encoding = detector.getDetectedCharset();
            detector.reset();
            if (encoding == null){
                encoding = defaultCharset;
            }else if ( encoding.equals("IBM855") || encoding.equals("WINDOWS-1252")) {
                encoding = "GBK";
            }
            return encoding;
        } catch (Exception e) {
            logger.error("无法获取编码格式", e);
        }
        return defaultCharset;
    }

    /**
     * 将当前字节数组的编码格式转成指定的格式，默认为utf-8
     * @出参： 转成指定格式后的字符串
     */
    public static String convertCharset(byte[] strData, String charsetName) throws UnsupportedEncodingException {
        // 获取编码格式
        String charset = getCharset(strData);
        // 转码
        String oldStr = new String(strData, charset);
        // 返回
        return new String(oldStr.getBytes(charsetName), charsetName);
    }
}
